import * as React from 'react';
import { createMaterialTopTabNavigator } from 'react-navigation-tabs';
import Albums from './Shared/Albums';
import Article from './Shared/Article';
import Contacts from './Shared/Contacts';
import Chat from './Shared/Chat';
import {
  Text,
  View,
  StyleSheet,
  TextInput,
  TouchableOpacity,
} from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';
// @ts-ignore
import TouchableBounce from 'react-native/Libraries/Components/Touchable/TouchableBounce';



let flag = true

// 动态设置图标大小
const TabBarIconSizeConfig = {
  size: 17, // 默认大小
  getSize: function () {
    return this.size;
  },
  setSize: function (newSize: number) {
    this.size = newSize;
  },
};

const tabBarIcon =
  (name: string) =>
  ({ tintColor, horizontal }: { tintColor: string; horizontal: boolean }) => (
    <MaterialIcons
      name={name}
      color={tintColor}
      size={TabBarIconSizeConfig.getSize() || (horizontal ? 17 : 24)}
    />
  );

class AlbumsScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Albums',
    // tabBarIcon: tabBarIcon('photo-album'),
    tabBarButtonComponent: TouchableBounce,
  };

  render() {
    return <Albums />;
  }
}

class ArticleScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Article',
    tabBarIcon: tabBarIcon('chrome-reader-mode'),
    tabBarButtonComponent: TouchableBounce,
  };

  render() {
    return <Article />;
  }
}

class ContactsScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Contacts',
    tabBarIcon: tabBarIcon('contacts'),
    tabBarButtonComponent: TouchableBounce,
  };

  render() {
    return <Contacts />;
  }
}

class ChatScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Chat',
    tabBarIcon: tabBarIcon('chat-bubble'),
    tabBarButtonComponent: TouchableBounce,
  };

  render() {
    return <Chat />;
  }
}

// 自定义顶部标签栏（含搜索框）
const CustomTopTabBar = props => {
  const {
    onTabPress,
    navigation,
    getLabelText,
    getAccessibilityLabel,
    getTestID,
    onIndexChange,
  } = props;
  const currentIndex = navigation.state.index;
  const { routes } = navigation.state;
  // console.log('props',props);
  // 定义标签名称与图标名称的映射关系
  const getTabIcon = routeName => {
    switch (routeName) {
      case 'Albums':
        return 'photo-album';
      case 'Article':
        return 'chrome-reader-mode';
      case 'Contacts':
        return 'contacts';
      case 'Chat':
        return 'chat';
      default:
        return 'help-outline';
    }
  };

  return (
    <View style={styles.topTabContainer}>
      {/* 左侧返回按钮 */}
      <AntDesign.Button
        name="arrowleft"
        size={20}
        // width={60}
        title="Go to Home"
        onPress={() => {
          navigation.navigate('Home');
        }}>
        Go to Home
      </AntDesign.Button>

      <View style={{ marginTop: 20 }} />

      {/* 搜索框 */}
      <TextInput
        style={styles.searchInput}
        placeholder="搜索内容..."
        placeholderTextColor="#999"
      />

      {/* 标签项容器 */}
      <View style={styles.tabsContainer}>
        {routes.map((route, index) => {
          const isActive = currentIndex === index;
          const iconName = getTabIcon(route.routeName);

          return (
            <TouchableOpacity
              key={route.key}
              style={styles.topTabItem}
              onPress={() => {
                onTabPress({ route: routes[index], index });
                // onTabLongPress({ route: routes[index], index });
                console.log(
                  'getLabelText',
                  getLabelText({ route: routes[index], index }),
                );
                console.log(
                  'getAccessibilityLabel',
                  getAccessibilityLabel({ route: routes[index], index }),
                );
                console.log(
                  'getTestID',
                  getTestID({ route: routes[index], index }),
                );
                console.log('onIndexChange == '+onIndexChange)
                // onIndexChange(index); //props中没有onIndexChange方法
                // renderScene // props中没有renderScene方法
                // renderIcon // renderIcon方法
                // descriptors // props中没有descriptors方法
              }}>
              {/* 2. 添加图标组件 */}
              <MaterialIcons
                name={iconName}
                color={isActive ? 'blue' : '#666'}
                size={TabBarIconSizeConfig.getSize()}
                style={styles.tabIcon}
              />
              <Text
                style={{
                  color: isActive ? 'blue' : '#666',
                  fontWeight: isActive ? 'bold' : 'normal',
                }}>
                {route.routeName}
              </Text>
              {/* 选中指示器 */}
              {isActive && <View style={styles.indicator} />}
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  topTabContainer: {
    backgroundColor: '#fff',
    padding: 20,
    marginTop: 20,
  },
  searchInput: {
    height: 36,
    backgroundColor: '#f5f5f5',
    borderRadius: 18,
    paddingHorizontal: 15,
    fontSize: 14,
    marginBottom: 10,
  },
  tabsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  topTabItem: {
    alignItems: 'center',
    paddingVertical: 5,
  },
  indicator: {
    height: 2,
    width: 20,
    backgroundColor: 'blue',
    marginTop: 5,
    borderRadius: 1,
  },
  tabIcon: {
    marginBottom: 4,
  },
});

// 2. 定义占位组件（未激活标签时显示）
const LazyPlaceholder = ({ route }) => {
  // 接收 route props，可显示当前标签名称

  return (
    <View style={lazyPlaceholderstyles.placeholder}>
      <Text style={lazyPlaceholderstyles.placeholderText}>
        加载中...（{route.name} 标签未激活）
      </Text>
    </View>
  );
};

const lazyPlaceholderstyles = StyleSheet.create({
  screen: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  placeholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  placeholderText: { color: '#999', fontSize: 14 },
});

const MaterialTopCustomTabs = createMaterialTopTabNavigator(
  {
    Albums: {
      screen: AlbumsScreen,
    },
    Article: {
      screen: ArticleScreen,
    },
    Contacts: {
      screen: ContactsScreen,
    },
    Chat: {
      screen: ChatScreen,
    },
  },
  {
    initialRouteName: 'Chat',
    // lazy: true, // 懒加载（仅在需要时加载屏幕）
    tabBarOptions: {
      style: {
        // backgroundColor: '#5620E4' // 标签栏背景颜色
      },
      labelStyle: {
        fontSize: 15, // 标签文字大小
      },
      tabStyle: {
        // width: 130, // 标签宽度
        height: 100, // 标签高度
        // backgroundColor: 'yellow', // 标签栏背景颜色（选中）
      },
      activeTintColor: 'red', // 标签文字颜色（选中）
      inactiveTintColor: 'pink', // 标签文字颜色（未选中）
      showIcon: true, // 是否显示图标
      showLabel: true, // 是否显示标签文字
      upperCaseLabel: true, // 是否将标签文字转换为大写
      pressColor: 'black', // 设置安卓设备上标签被点击时的水波纹颜色(Android >= 5.0 only)
      pressOpacity: 0.3, // 标签点击时的透明度（0-1）
      scrollEnabled: false, // 是否允许标签栏滚动
      indicatorStyle: {
        backgroundColor: 'green', // 标签栏指示器颜色（底部高亮条）
        height: 10, // 标签栏指示器高度
      },
      iconStyle: {
        fontSize: TabBarIconSizeConfig.setSize(15), // 标签栏图标大小
      },
      allowFontScaling: true, 
    },
    tabBarPosition: 'top', // 标签栏位置（顶部）
    // keyboardDismissMode: 'none' , // none键盘消失模式（不消失）'on-drag': 页面滑动消失
    keyboardDismissMode: flag?'none':'on-drag', // none键盘消失模式（不消失）'on-drag': 页面滑动消失
    swipeEnabled: true, // 开启滑动切换标签功能
    swipeDistanceThreshold: 1, 
    swipeVelocityThreshold: 1, 
    initialLayout: { width: '200', height: '300' }, 
    lazy: false, // 懒加载（仅在需要时加载屏幕）
    lazyPlaceholderComponent: LazyPlaceholder, // 配置占位组件
    tabBarComponent: CustomTopTabBar, // 自定义标签栏
    style: {
      // 设置组件自身的样式，作用于当前组件的根容器（组件本身的最外层视图）
      // backgroundColor: 'yellow',
      // marginTop: 20
    },
    onSwipeStart: () => {
      // 滑动开始时调用
      console.log('onSwipeStart:', '开始滑动');
    },
    onSwipeEnd: () => {
      // 滑动结束时调用
      console.log('onSwipeEnd:', '滑动结束');
    },
  },
);

export default MaterialTopCustomTabs;